﻿using System.Globalization;
using LY.Business.ServiceImpl;
using LY.Common;
using LY.Entity;
using LY.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Nancy;
using Nancy.ModelBinding;

namespace Sys.API.Models
{
    public class MemberModule : BaseModule
    {
        readonly IMemberService _memberService = new MemberService();

        public MemberModule() :
            base("/Member")
        {
            Get["/"] = paramaters =>
          {   

              return "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'/><title>接口API</title></head><body> <h1>接口API[2015-07-28]</h1></body></html> ";
          };
            Post["/LoginName"] = _ =>
            {
                //第三方登陆
                var memberInfo = this.Bind<MemberInfo>();

                if (memberInfo.Id==0)
                {
                    return Response.AsJson(CreateWebApiMsg(-1, "参数有误", ""));
                } 

                var user_info = _memberService.getMemberInfo((int)memberInfo.Id);
                if (user_info != null)
                {
                    return Response.AsJson(CreateWebApiMsg(1, "OK", user_info));
                }
                else
                {
                    return Response.AsJson(CreateWebApiMsg(-1, "参数有误！"));
                }
            };
            Post["/Login.do"] = _ =>
            {
                //用户登陆
                var memberInfo=this.Bind<MemberInfo>();
                //var appid = (string)this.Request.Form.AccessToken;
                if (string.IsNullOrEmpty(memberInfo.Phone) || string.IsNullOrEmpty(memberInfo.Password))
                {
                    return Response.AsJson(CreateWebApiMsg(-1, "参数有误", ""));
                }

                var user_info = _memberService.login(memberInfo.Phone, memberInfo.Password);
                 if (user_info != null)
                 { 
                     return Response.AsJson(CreateWebApiMsg(1, "OK", user_info));
                 }
                 else
                 {
                     return Response.AsJson(CreateWebApiMsg(-1, "用户名/密码有误！"));
                 }
            };
            Post["/OauthLogin.do"] = _ =>
            {
                //第三方登陆
                var Info = this.Bind<U_Member_oauth>();
                //var appid = (string)this.Request.Form.AccessToken;
                if (string.IsNullOrEmpty(Info.oauth_name) || string.IsNullOrEmpty(Info.oauth_openid))
                {
                    return Response.AsJson(CreateWebApiMsg(-1, "参数有误", ""));
                }
                var user_info = _memberService.OauthLogin(Info.oauth_name, Info.oauth_openid);
                if (user_info != null)
                {
                    return Response.AsJson(CreateWebApiMsg(1, "OK", user_info));
                }
                else
                {
                    return Response.AsJson(CreateWebApiMsg(-1, "用户名/密码有误！"));
                }
            };
            Post["/Register.do"] = _ =>
            {
                //注册
                var memberInfo = this.Bind<MemberInfo>();
                //var appid = (string)this.Request.Form.AccessToken;
                if (memberInfo == null)
                {
                    return Response.AsJson(CreateWebApiMsg(-1, "参数有误", ""));
                }
                if (_memberService.ExistsPhone(memberInfo.Phone))
                {
                    return Response.AsJson(CreateWebApiMsg(-1, "手机已注册", ""));
                }
                if (string.IsNullOrEmpty(memberInfo.Phone))
                {
                    return Response.AsJson(CreateWebApiMsg(-1, "手机号不能为空", ""));
                }
                if (string.IsNullOrEmpty(memberInfo.Password))
                {
                    return Response.AsJson(CreateWebApiMsg(-1, "密码不能为空", ""));
                } 
                var memberModel = new LY.Entity.U_Member
                    {
                        Mobilenumber = memberInfo.Phone,
                        Password = memberInfo.Password, 
                        Name = "CJ"+memberInfo.Phone.Substring(memberInfo.Phone.Length-4,4)+LY.Common.Utility.Number(4),
                        RegistrationTime = DateTime.Now,
                        InputTime = DateTime.Now,
                        LastLoginTime = DateTime.Now,
                        ClientSource = "手机",
                        Nickname = "CJ" + memberInfo.Phone.Substring(memberInfo.Phone.Length - 4, 4) + LY.Common.Utility.Number(4) 
                    };

                int flag=    _memberService.SaveMember(memberModel);  
                if (flag > 0)
                {
                    ISysTemplateService templateService = new SysTemplateService();
                    var templateModel = templateService.GetSysTemplate("welcomesms");
                    string smstemp = templateModel.TemplateContent;
                    smstemp = smstemp.Replace("{webname}", "全局金服");
                    smstemp = smstemp.Replace("{username}", memberInfo.Phone);
                    var m = "";
                    SmsMessage.Send(memberInfo.Phone, smstemp, 1, out m); 
                    IScoreService _scoreService =new ScoreService();
                    _scoreService.SaveScore("注册", flag); 
                    return Response.AsJson(CreateWebApiMsg(1, "OK", flag.ToString()));
                }
                else
                    return Response.AsJson(CreateWebApiMsg(-1, "注册失败", ""));
            };
            Post["/RegMemberOauth.do"] = _ =>
            {
                var memberInfo = this.Bind<U_Member_oauth>();   
                var memberModel = new LY.Entity.U_Member_oauth  
                {
                    oauth_name = memberInfo.oauth_name,
                    user_id = memberInfo.user_id,
                    user_name = memberInfo.user_name,
                    oauth_access_token = memberInfo.oauth_access_token,
                    oauth_openid = memberInfo.oauth_openid,
                    add_time = DateTime.Now
                };

                int flag = _memberService.SaveMemberOauth(memberModel);
                if (flag > 0)
                { 
                    return Response.AsJson(CreateWebApiMsg(1, "OK", flag.ToString()));
                }
                else
                    return Response.AsJson(CreateWebApiMsg(-1, "第三方绑定失败", ""));
            };
            Post["/EditMember.do"] = _ =>
            {
                var memberInfo = this.Bind<MemberInfo>();
                if (memberInfo == null)
                {
                    return Response.AsJson(CreateWebApiMsg(-1, "参数有误", ""));
                } 
                return Response.AsJson(CreateWebApiMsg(1, "修改成功", ""));
            };
          
        }
        /// <summary>
        /// 生成LoginNo
        /// </summary>
        /// <returns></returns>
          private string GenerateLoginNo()
         {
            long i = 1;
            foreach (byte b in Guid.NewGuid().ToByteArray())
            {
                i *= ((int)b + 275);
            }
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }
         private long GenerateIntID()

        {

            byte[] buffer = Guid.NewGuid().ToByteArray();

            return BitConverter.ToInt64(buffer, 0);

        }
        private class MemberInfo {
            public long Id { get; set; }
            public string Org_AppId { get; set; }
            public string Login_No { get; set; }
            public string Nick_Name { get; set; }
            public string Real_Name { get; set; }
            public string Gender { get; set; }
            public string Birthday { get; set; }
            public string Phone { get; set; }
            public string Status { get; set; }
            public string Email { get; set; }
            public string RegisterDate { get; set; }
            public string Address { get; set; }
            public string Password { get; set; }
            public int Type { get; set; }
            public string Province { get; set; }
            public string City { get; set; }
        
        }
    }
}